package com.itheima.reggie.controller;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.common.Result;
import com.itheima.reggie.dto.DishDto;
import com.itheima.reggie.entity.Category;
import com.itheima.reggie.entity.Dish;
import com.itheima.reggie.entity.DishFlavor;
import com.itheima.reggie.service.CategoryService;
import com.itheima.reggie.service.DishFlavorService;
import com.itheima.reggie.service.DishService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;
import java.util.List;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
* 菜品管理
* */
@Slf4j
@RestController
@RequestMapping("/dish")
public class DishController {
    @Autowired
    private DishFlavorService dishFlavorService;

    @Autowired
    private DishService dishService;

    @Autowired
    private CategoryService categoryService;

    @Autowired
    private RedisTemplate redisTemplate;


    /**
     * 新增菜品
     * @param dishDto
     * @return
     */
    @PostMapping
    public Result<String> save(@RequestBody DishDto dishDto){

        log.info(dishDto.toString());

        dishService.saveWithFlavor(dishDto);

        return Result.success("新增菜品成功");
    }

    /**
     * 菜品信息的分页查询
     * @param page
     * @param pageSize
     * @param name
     * @return
     */
    @GetMapping("/page")
    public Result<Page> page(int page, int pageSize,String name){

        //构造分页构造器对象
        Page<Dish> pageInfo = new Page<>(page, pageSize);

        Page<DishDto> dishDtoPage = new Page<>();//本来返回值为pageInfo,因为少了categoryName所以不满足要求，所以改变了返回值的类型，改成了dishDtoPage

        //条件构造器
        LambdaQueryWrapper<Dish> queryWrapper = new LambdaQueryWrapper<>();

        //添加过滤条件
        queryWrapper.like(name!=null,Dish::getName,name);

        //添加排序条件
        queryWrapper.orderByDesc(Dish::getUpdateTime);

        dishService.page(pageInfo,queryWrapper);

        //对象拷贝
        BeanUtils.copyProperties(pageInfo,dishDtoPage,"records");//将pageInfo对象中的属性拷贝到dishDtoPage，忽略掉records属性

        List<Dish> records = pageInfo.getRecords();

        List<DishDto> list=records.stream().map((item)->{ //变量得到菜品名称等所有信息

            DishDto dishDto=new DishDto();

            BeanUtils.copyProperties(item,dishDto);//把普通属性（除了categoryName）也拷贝进去

            Long categoryId = item.getCategoryId();//分类id

            //根据id来查询分类对象
            Category category = categoryService.getById(categoryId);

            if(category!=null){
                String categoryName = category.getName();
                dishDto.setCategoryName(categoryName);//由于此dishDto是自己new的，只把菜品名称categoryName这个属性传进去，dishDto继承dish中的其他属性并没有传进去，所以要执行BeanUtils.copyProperties(item,dishDto);
            }

            return dishDto;

        }).collect(Collectors.toList());

        dishDtoPage.setRecords(list);

        return Result.success(dishDtoPage);
    }


    /**
     * 根据id查询菜品信息和对应的口味信息
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    public Result<DishDto> get(@PathVariable Long id){ //因为路径变量id是可变的，需要用{}括起来，所以要用到路径变量注解@PathVariable

        DishDto dishDto = dishService.getByIdWithFlavor(id);

        return Result.success(dishDto);
    }

    /**
     * 修改菜品
     * @param dishDto
     * @return
     */
    @PutMapping
    public Result<String> update(@RequestBody DishDto dishDto){

        log.info(dishDto.toString());

        dishService.updateWithFlavor(dishDto);
        
       /* //清理所有菜品的缓存数据
        Set keys = redisTemplate.keys("dish_*");
        redisTemplate.delete(keys);*/

        /* 清理某个分类下的菜品缓存数据 */
        String key="dish_" + dishDto.getCategoryId() + "_1";
        redisTemplate.delete(key);


        return Result.success("修改菜品成功");

    }


    /**
     * 根据条件查询对应的菜品数据
     * @param dish
     * @return
     */
  /*  @GetMapping("/list")
    public Result<List<Dish>> list(Dish dish){ //用Long类型也可以，但为了保证通用性，使得传Dish中的任意属性都能接收，所以用Dish类型
        //条件构造器
        LambdaQueryWrapper<Dish> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(dish.getCategoryId()!=null,Dish::getCategoryId,dish.getCategoryId());//(实体类)Dish::(类中属性)getCategoryId等值查询

        //添加条件，查询状态为1(起售状态)的菜品
        queryWrapper.eq(Dish::getStatus,1);

        //添加排序条件
        queryWrapper.orderByAsc(Dish::getSort).orderByDesc(Dish::getUpdateTime);

        List<Dish> list = dishService.list(queryWrapper);


        return Result.success(list);

    }*/

    @GetMapping("/list")
    public Result<List<DishDto>> list(Dish dish){ //用Long类型也可以，但为了保证通用性，使得传Dish中的任意属性都能接收，所以用Dish类型
        List<DishDto> dishDtoList=null;

        String key="dish_" + dish.getCategoryId() + "_" + dish.getStatus();//动态构造一下key, dish_1397844303408574465_1
        
        //先从redis中获取缓存数据
        dishDtoList = (List<DishDto>) redisTemplate.opsForValue().get(key);


        if(dishDtoList!=null){
            //如果存在，直接返回，无需查询数据库

            return Result.success(dishDtoList);
        }


        //条件构造器
        LambdaQueryWrapper<Dish> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(dish.getCategoryId()!=null,Dish::getCategoryId,dish.getCategoryId());//(实体类)Dish::(类中属性)getCategoryId等值查询

        //添加条件，查询状态为1(起售状态)的菜品
        queryWrapper.eq(Dish::getStatus,1);

        //添加排序条件
        queryWrapper.orderByAsc(Dish::getSort).orderByDesc(Dish::getUpdateTime);

        List<Dish> list = dishService.list(queryWrapper);

        dishDtoList=list.stream().map((item) -> { //变量得到菜品名称等所有信息

            DishDto dishDto=new DishDto();

            BeanUtils.copyProperties(item,dishDto);//把普通属性（除了categoryName）也拷贝进去

            Long categoryId = item.getCategoryId();//分类id

            //根据id来查询分类对象
            Category category = categoryService.getById(categoryId);

            if(category!=null){
                String categoryName = category.getName();
                dishDto.setCategoryName(categoryName);//由于此dishDto是自己new的，只把菜品名称categoryName这个属性传进去，dishDto继承dish中的其他属性并没有传进去，所以要执行BeanUtils.copyProperties(item,dishDto);
            }

            Long dishId = item.getId();//获取当前菜品的id
            LambdaQueryWrapper<DishFlavor> lambdaQueryWrapper = new LambdaQueryWrapper<>();
            lambdaQueryWrapper.eq(DishFlavor::getDishId,dishId);
            //SQL:select * from dish_flavor where dish_id=?
            List<DishFlavor> dishFlavorList = dishFlavorService.list(lambdaQueryWrapper);//根据条件查询菜品口味集合
            dishDto.setFlavors(dishFlavorList);
            return dishDto;
        }).collect(Collectors.toList());

        //List<DishDto> dishDtoList=null;


         //如果不存在，需要查询数据库，将查询到的菜品数据缓存到Redis中
        redisTemplate.opsForValue().set(key,dishDtoList,60, TimeUnit.MINUTES);//缓存1小时

        return Result.success(dishDtoList);

    }
}
//报500错的，注释redis配置文件中的value的序列化，再清空redis